package com.lin.base;

import com.fasterxml.jackson.core.JsonParseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;

/**
 * @Author Created by Lin Weihong
 * @Time on 2022/1/21 1:32
 */
@Slf4j
@RestControllerAdvice //捕获RestController的异常
public class GlobalExceptionHandler {


    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(SQLException.class)
    public Result handler(SQLException e) {
        log.info("数据库异常:---------------------{}", e.getMessage());
        return Result.fail(e.getMessage());
    }


    //实体校验异常
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result handler(MethodArgumentNotValidException e) {
        //result当中含有异常的信息
        BindingResult result = e.getBindingResult();
        ObjectError error = result.getAllErrors().stream().findFirst().get();
        log.info("实体校验异常:---------------------{}", error.getDefaultMessage());
        return Result.fail(error.getDefaultMessage());
    }

    //非法数据异常
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = IllegalArgumentException.class)
    public Result handler(IllegalArgumentException e) {
        log.info("Assert异常:---------------------{}", e.getMessage());
        return Result.fail(e.getMessage());
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST) //返回的状态码
    @ExceptionHandler(value = JsonParseException.class)
    public Result handler(JsonParseException e) {
        log.info("Json解析异常:---------------------{}", e.getMessage());
        return Result.fail(e.getMessage());
    }

    //运行异常
    @ResponseStatus(HttpStatus.BAD_REQUEST) //返回的状态码
    @ExceptionHandler(value = RuntimeException.class)//捕获RuntimeException异常
    public Result handler(RuntimeException e) {
        if (e.getMessage() == null) {
            log.info("运行时异常:---------------------{}", "处理异常");
            return Result.fail("处理异常");
        }
        log.info("运行时异常:---------------------{}", e.getMessage());
        return Result.fail(e.getMessage());
//        return Result.fail("系统运行异常");
    }


}
